package com.inspectortime.domain.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.inspectortime.BaseSpringContextAwareTestCase;

public abstract class BaseHibernateEntityTestCase extends
		BaseSpringContextAwareTestCase {

	private SessionFactory sessionFactory;

	protected SessionFactory getSessionFactory() {
		return this.sessionFactory;
	}

	/**
	 * Flush and clear hibernate cache just to make sure the loaded instance is
	 * fetched from the db and not hibernate cache
	 */
	protected void clearHibernate() {
		Session session = SessionFactoryUtils.getSession(getSessionFactory(),
				true);
		session.flush();
		session.clear();
	}

	public void setUp() throws Exception {
		
		/* 2/27/12: Fails due to spring/hibernate jar upgrade. May want to bring this back at some point.
		super.setUp();
		this.sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
		assertNotNull(
				"Spring context did not declare a required 'sessionFactory' bean",
				this.sessionFactory);

		// Bind a session to ThreadLocal for use by this thread
		Session session = SessionFactoryUtils.getSession(sessionFactory, true);
		TransactionSynchronizationManager.bindResource(this.sessionFactory,
				new SessionHolder(session));
				*/
	}

	public void tearDown() throws Exception {
		super.tearDown();

		/* 2/27/12: Fails due to spring/hibernate jar upgrade. May want to bring this back at some point.
		
		// Unbind session from ThreadLocal and release session
		Session session = SessionFactoryUtils.getSession(this.sessionFactory,
				true);
		TransactionSynchronizationManager.unbindResource(this.sessionFactory);
		SessionFactoryUtils.releaseSession(session, this.sessionFactory);
		
		*/
	}

}
